<template>
  <div class="app-container">
    <!-- 主体部分，包含左侧树形结构和右侧表格 -->
    <div style="display: flex">
      <!-- 左侧树形结构 -->
      <div>
        <div class="head-container">
          <el-input
            v-model="filterText"
            placeholder="输入关键字进行过滤"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 5px"
          />
        </div>
        <div class="head-container">
          <el-tree
            style="
              width: 300px;
              height: calc(100vh - 185px);
              overflow: auto;
              padding: 10px 0px;
            "
            v-if="treeLoad"
            :data="fitlerDeptOptions"
            :props="defaultProps"
            ref="tree"
            node-key="id"
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
            @node-contextmenu="handleContextmenu"
          />
        </div>
      </div>

      <!-- 右侧表格和操作按钮 -->
      <div style="overflow: hidden; margin-left: 15px; flex: 1">
        <!-- 操作按钮 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-search"
              size="mini"
              @click="handleSearch"
              >搜索</el-button
            >
          </el-col>
          <el-col :span="1.5" v-hasPermi="['product:productMstr:add']">
            <!-- <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button> -->
          </el-col>
        </el-row>
        <el-card style="height: calc(100vh - 185px); overflow: auto">
          <template #header>
            <div style="display: flex; justify-content: space-between">
              <span>{{ curNode.totalAndLabel }}设置</span>
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="submitForm"
                >保存</el-button
              >
            </div>
          </template>
          <div>
            <el-form
              ref="form"
              :model="form"
              label-width="120px"
              class="form-con"
            >
              <el-form-item
                v-for="(item, index) in curNode.configs"
                :key="index"
                :label="item.label"
                :prop="item.key"
                :required="item.required"
                :rules="item.rules"
              >
                <component
                  :is="item.component"
                  v-model="form[item.key]"
                  v-bind="item.attrs"
                />
                <span v-if="item.tip" style="color: #999; margin-left: 10px">{{
                  item.tip
                }}</span>
              </el-form-item>
              <div style="clear: both"></div>
            </el-form>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import * as api from "@/api/system/config";

export default {
  name: "UserConfig",
  data() {
    return {
      defaultProps: {
        children: "children",
        label: "totalAndLabel",
      },
      deptOptions: [
        {
          label: "全部",
          totalAndLabel: "系统参数",
          id: "sys",
          configs: [
            {
              label: "系统名称",
              key: "sysName",
              component: "el-input",
              required: true,
            },
            {
              label: "企业名称",
              key: "companyName",
              component: "el-input",
              required: true,
            },
            {
              label: "企业简称",
              key: "companyShortName",
              component: "el-input",
              required: true,
            },
            {
              label: "唯一码生成上限",
              key: "unique",
              component: "el-input-number",
              rules: [
                {
                  validator: (rule, value, callback) => {
                    if (Number.isInteger(value) && value >= 1) {
                      callback();
                    } else {
                      callback(new Error("请输入大于0的正整数"));
                    }
                  },
                  trigger: "blur",
                },
              ],
            },
            {
              label: "企业logo",
              key: "companyLogo",
              component: "ImageUpload",
              attrs: { limit: 1 },
              required: true,
            },
          ],
        },
        {
          label: "全部",
          totalAndLabel: "决策驾驶舱",
          id: "board",
          configs: [
            {
              label: "企业简介",
              key: "companyInfo",
              component: "el-input",
              attrs: { type: "textarea" },
              required: true,
            },
            {
              label: "产品照片",
              key: "proImg",
              component: "ImageUpload",
              attrs: { limit: 10, multiple: true },
              required: true,
            },
            {
              label: "企业照片",
              key: "companyImg",
              component: "ImageUpload",
              attrs: { limit: 10 },
              required: true,
            },
            {
              label: "技术人员",
              key: "companyPeoNum",
              component: "el-input",
              required: true,
            },
            {
              label: "销量系数",
              key: "coefficientSales",
              component: "el-input",
              required: true,
            },
            {
              label: "产量系数",
              key: "coefficientProd",
              component: "el-input",
              required: true,
            },
          ],
        },
        {
          label: "全部",
          totalAndLabel: "基础资料参数",
          id: "base",
          children: [],
        },
        {
          label: "全部",
          totalAndLabel: "采购参数",
          id: "purchase",
          children: [],
        },
        { label: "全部", totalAndLabel: "销售参数", id: "sale", children: [] },
        {
          label: "全部",
          totalAndLabel: "生产参数",
          id: "production",
          children: [],
        },
        {
          label: "全部",
          totalAndLabel: "库存参数",
          id: "inventory",
          configs: [
            {
              label: "库存审核开关",
              key: "check",
              component: "el-switch",
              tip: "开启时允许库存审核，关闭不允许库存审核",
              required: true,
            },
          ],
        },
      ],
      filterText: "",
      productList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: 0,
      },
      loading: false,
      total: 0,
      dialog: false,
      title: "",
      form: {},
      rules: {},
      treeLoad: false,
      treeLoad: true,
      curNode: {},
      curNodeKey: null,
      expandedKey: [0],
    };
  },
  created() {},

  computed: {
    fitlerDeptOptions() {
      if (!this.filterText) return this.deptOptions;
      return this.deptOptions.filter(
        (o) => o.totalAndLabel.indexOf(this.filterText) !== -1
      );
    },
  },
  methods: {
    // 表单重置
    reset() {
      this.form = {
        productId: null,
        productName: null,
        productRfid: null,
        productMsg: null,
        productModel: null,
        productZsm: null,
        productCpbm: null,
        productPh: null,
        productSmyz: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        productZtbz: null,
        productType: null,
        productCustomer: null,
        productSysc: null,
        productCcrq: this.$moment().format(),
        productDesc: null,
        productHgz: null,
        productSybg: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.productList = [];
      this.getList();
      this.openSearch = false;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.productId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加产品信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const productId = row.productId || this.ids;
      getProductMstrById(productId).then((response) => {
        response.data.productSysc = (
          response.data.productSysc / 3600000
        ).toFixed(2);
        response.data.productSmyz = (
          response.data.productSmyz / 3600000
        ).toFixed(2);
        this.form = response.data;
        this.open = true;
        this.title = "修改产品信息";
      });
    },
    handleSearch() {
      this.reset();
      this.title = "查询产品信息";
      this.openSearch = true;
    },
    getContainer(item) {
      //this.form.productZsm = item.itemFromCode
      this.form.productCpbm = item.itemDrawingCode;
      this.form.productName = item.itemName;
      this.form.productModel = item.itemProductModel;
      this.form.productType = item.productName;
      this.form.productMsg =
        this.form.productZsm +
        "/" +
        this.form.productName +
        "/" +
        this.form.productModel;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const arr = this.curNode.configs.map((o) => {
            return {
              configName: o.label,
              configKey: `cus.${this.curNode.id}.${o.key}`,
              configValue: this.form[o.key],
              configType: "N",
            };
          });
          api.batchSaveOrUpate(arr).then((response) => {
            this.$modal.msgSuccess("操作成功");
          });
        }
      });
    },

    getTreeselect() {
      const callback = (response) => {
        const tree = this.$refs.tree;
        const tmpKey = tree.getCurrentKey();
        if (tmpKey) {
          this.expandedKey = [tmpKey];
          this.$nextTick(() => {
            tree.setCurrentKey(tmpKey);
          });
        }
        var tmp = [];
        response.data = {
          id: 0,
          totalAndLabel: "全部",
          parentId: null,
          children: response.data,
        };
        tmp.push(Object.assign({}, this.deptOptions[0], response.data));
        this.deptOptions = tmp;
        //this.treeLoad = true
        this.getList();
      };

      treeSelect().then(callback);
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.curNode = data;
      const configKey = "cus." + data.id;
      api.listByConfigKey(configKey).then((res) => {
        this.form = res.data;
        this.form.check == "false"
          ? (this.form.check = false)
          : (this.form.check = true);
      });
    },

    handleContextmenu(event, data) {
      if (!data.parentId) return false;
      console.log(data);
      this.$contextmenu({
        items: [
          {
            label: "设置寿命阈值",
            icon: "el-icon-edit",
            onClick: () => {
              this.$prompt(`请输入${data.label}的寿命阈值(小时)`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                inputType: "number",
                inputPattern: /^[+]{0,1}(\d+)$/,
                inputErrorMessage: "输入格式不正确",
              }).then(({ value }) => {
                updateProductByCustomer({
                  productCustomer: data.parentId,
                  productType: data.id,
                  productSmyz: parseInt(value),
                }).then((res) => {
                  this.msgSuccess(res.msg);
                  //this.getList()
                });
                console.log(value);
              });
            },
          },
        ],
        event,
        //x: event.clientX,
        //y: event.clientY,
        //customClass: "custom-class",
        zIndex: 3,
        //minWidth: 230,
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.totalAndLabel.indexOf(value) !== -1;
    },
  },
};
</script>

<style lang="scss" scoped>
.head-container {
  ::v-deep .el-tree-node__children {
    width: fit-content;
  }
}
</style>
